"use strict";
const Service = require("egg").Service;
const { httpCode } = require("../../utils/userConfig")
const SystemErrException = require("../../exception/systemError");
const path = require('path');
const fs = require('fs');
const moment = require("moment");
const awaitWriteStream = require("await-stream-ready").write;
const { getVideoTime } = require("../../utils/helpFull")


class FileService extends Service {

  async deleteFile(requestData) {
    try {
      let { ctx } = this;
      let { url, belongTo, name } = requestData;
      let imgName;
      if (url) {
        let urlArr = url.split('medias/');
        imgName = urlArr[1];
      }
      if (name) {
        imgName = name;
      }

      let imgPath = path.join(__dirname, "../../public/medias/", imgName);
      if (fs.existsSync(imgPath)) {
        fs.unlinkSync(imgPath);
      }
      return {
        data: true,
        code: httpCode.SUCCESS,
        message: '图片删除成功！'
      }
    } catch (error) {
      throw new SystemErrException("文件删除异常：" + error);
    }
  }

  async uploadFile() {
    try {
      const { ctx } = this;
      const stream = await ctx.getFileStream({ requireFile: false });
      let filename = stream.filename;
      let filenames = filename.split('.');
      let belongTo = stream.fields.belongTo;
      let currentTime = moment(new Date()).format('YYYYMMDDHHmmss');
      let mediaName = `${belongTo}-${currentTime}.${filenames[1]}`;
      const localFilePath = path.join(__dirname, "../../public/medias", mediaName);
      const writeStream = fs.createWriteStream(localFilePath);
      await awaitWriteStream(stream.pipe(writeStream));
      let url = `${ctx.app.config.userConfig.mediasBaseUrl}/${mediaName}`;

      let data;
      data = url;
      if (belongTo == 'courseMedia-mediaUrl') {
        let videoSeconds = await getVideoTime(localFilePath);
        data = {
          url,
          videoSeconds
        }
      }

      return {
        data,
        code: httpCode.SUCCESS,
        message: '图片添加成功！'
      }
    } catch (error) {
      throw new SystemErrException("添加异常：" + error);
    }
  }
}

module.exports = FileService;
;